import { ref } from 'vue';
import commentApi from '@/api/comment';

export default () => {
  const commentList = ref([]);
  const commentTotal = ref(0);
  const getCommentList = ({
    publish_id,
    target_type,
    target_id,
    page,
    size,
  }) => {
    return commentApi
      .getCommentList({
        publish_id,
        target_type,
        target_id,
        page,
        size,
      })
      .then((res) => {
        commentTotal.value = res.data.total;
        return res.data.list;
      });
  };

  const createComment = ({
    context,
    publish_id,
    target_type,
    target_id,
    page,
    size,
    content,
    parentConfirmItem,
    parentConfirmReplyItem,
  }) => {
    const getToUserId = () => {
      return (
        parentConfirmReplyItem.value.user?.id ||
        parentConfirmItem.value.user?.id
      );
    };
    return commentApi
      .createComment({
        publish_id,
        target_type,
        target_id,
        page,
        size,
        content,
        to_user_id: getToUserId(),
      })
      .then((res) => {
        uni.showToast({
          title: '评论成功',
          icon: 'none',
          mask: false,
        });
        if (parentConfirmItem.value.id) {
          if (!parentConfirmItem.value.reply_list) {
            parentConfirmItem.value.reply_list = [];
          }
          parentConfirmItem.value.reply_list.push(res.data);
        } else {
          commentTotal.value += 1;
          context.addDataFromTop(res.data, true, true);
        }
        return res;
      });
  };

  return {
    getCommentList,
    createComment,
    commentList,
    commentTotal,
  };
};
